package com.xb;

/**
 * @program: register-jerry
 * @description: ThreadLocal 例子使用
 * @author: xu.bin
 * @create: 2020-11-15
 */
/**
 * ThreadLocal源码相对简单
 * 一般而言，只需要去看看set get实现方法即可
 *JDK 内部有个一个ThreadMap内部类，每个线程对象内部，有个核心的对象，
 * 通过map<threadId,value>去实现我们的线程不共享，所以是非常的建单
 */
public class ThreadLocalDemo {
    public static class ThreadVar{
        String name;
        String age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

        public ThreadVar(String name, String age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "ThreadVar{" +
                    "name='" + name + '\'' +
                    ", age='" + age + '\'' +
                    '}';
        }
    }
    static public void main(String []args){
        ThreadLocal<Long> requestId=new InheritableThreadLocal<>();
        ThreadLocal<ThreadVar> threadVarInheritableThreadLocal=new InheritableThreadLocal<>();
        new Thread(){
            @Override
            public void run() {
                requestId.set(100L);
                threadVarInheritableThreadLocal.set(new ThreadVar("xiaohei","20"));
                System.out.println("线程:"+Thread.currentThread()+"请求变量是"+requestId.get());
                System.out.println("线程:"+Thread.currentThread()+"请求对象是"+threadVarInheritableThreadLocal.get().toString());
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                requestId.set(200L);
                ThreadLocal<ThreadVar> threadVarInheritableThreadLocal=new InheritableThreadLocal<>();
                threadVarInheritableThreadLocal.set(new ThreadVar("xiaolan","10"));
                System.out.println("线程:"+Thread.currentThread()+"请求变量是"+requestId.get());
                System.out.println("线程:"+Thread.currentThread()+"请求对象是"+threadVarInheritableThreadLocal.get().toString());
            }
        }.start();
    }
}